package com.tianma.upload.uploadjartest.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @author lgc
 * @createDate 2020/8/4 - 18:02
 */
//道高一尺魔高一丈
public class LazyMan {
   private static boolean cunzai = false;
   private LazyMan(){
      synchronized (LazyMan.class){
          if (cunzai == false){
              cunzai = true;
          }else {
              throw new RuntimeException("不要试图利用反射破坏单例");
          }
      }
   }
   //添加volatile保证 禁止指令重排
   private volatile static  LazyMan lazyMan;

   //双重检测锁模式，懒汉式模式 DCL懒汉式
   public static LazyMan getInstance(){
       if (lazyMan==null){
           synchronized (LazyMan.class){
               if (lazyMan==null){
                   lazyMan = new LazyMan();//不是原子性操作，
                   /**
                    * 底层可能指令重排了
                    * 1.分配内存空间
                    * 2.执行构造方法，初始化对象
                    * 3.把这个对象指向这个空间
                    */
               }
           }
       }
       return lazyMan;
   }
   public static void main(String[] args){
            /*Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
                   constructor.setAccessible(true);
                   LazyMan lazyMan = constructor.newInstance();*/
       try {
           LazyMan lazyMan = null;
           lazyMan = LazyMan.class.newInstance();
           System.out.println(lazyMan);
           Field cunzai = LazyMan.class.getDeclaredField("cunzai");
           cunzai.set(lazyMan,false);
           Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor();
           LazyMan lazyMan1 = declaredConstructor.newInstance();
           System.out.println(lazyMan1);
       } catch (Exception e) {
           e.printStackTrace();
       }


   }
}
